<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="800" @ok="handleSubmit">
    <BasicForm @register="registerForm" ref="formRef" name="GoodfishOrderForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed, unref, reactive } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods.ts';
  import { cardColumns } from '../GoodfishOrder.data';
  import { jiHuoSchema } from '../GoodfishOrder.data';
  import { jiHuo, cardList } from '../GoodfishOrder.api';
  // Emits声明
  const emit = defineEmits(['register', 'success']);
  const isUpdate = ref(true);
  const formDisabled = ref(false);
  const orderNo = ref('');
  const activeKey = ref('card');
  const card = ref();
  const cardTable = reactive({
    loading: false,
    dataSource: [],
    columns: cardColumns,
  });
  //表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 150,
    schemas: jiHuoSchema,
    showActionButtonGroup: false,
    baseColProps: { span: 24 },
  });
  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //重置表单
    await reset();
    setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
    isUpdate.value = !!data?.isUpdate;
    orderNo.value = data.orderNo;
      await setFieldsValue({
        ...data.record,
      });
    formDisabled.value = !data?.showFooter;
    // 隐藏底部时禁用整个表单
    setProps({ disabled: !data?.showFooter });
  });
  //方法配置

  //设置标题
  const title = computed(() => (!unref(isUpdate) ? '激活' : !unref(formDisabled) ? '激活' : '激活'));

  async function reset() {
    await resetFields();
    activeKey.value = 'card';
    cardTable.dataSource = [];
  }
  function classifyIntoFormData(allValues) {
    let main = Object.assign({}, allValues.formValue);
    return {
      ...main, // 展开
      cardList: allValues.tablesValue[0].tableData,
    };
  }
  //表单提交事件
  async function handleSubmit(v) {
    try {
      let values = await validate();
      values.orderNo = orderNo.value;

      setModalProps({ confirmLoading: true });
      //提交表单
      await jiHuo(values, isUpdate.value);

      closeModal();
      //刷新列表
      emit('success');
    } catch ({ errorFields }) {
      closeModal();
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>

<style lang="less" scoped>
  /** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.ant-calendar-picker) {
    width: 100%;
  }
</style>
